package afcp.alumni.action.page;

import java.util.LinkedList;
import java.util.List;

import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.security.Secure;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import afcp.alumni.action.base.PageAction;
import afcp.alumni.action.event.ManageMemberAction;
import afcp.alumni.action.event.UploadMemberFileAction;
import afcp.alumni.model.SearchResult;
import afcp.alumni.model.db.CsvColumn;
import afcp.alumni.model.db.Member;
import afcp.alumni.model.db.Role;
import afcp.alumni.service.MemberService;
import afcp.alumni.service.SF;
import afcp.alumni.util.Charsets;
import afcp.alumni.util.Conf;

@UrlBinding(value = AdminAction.URL)
@Secure(roles = MemberService.ROLE_ADMIN)
public class AdminAction extends PageAction {

	@Override
	public String getUrl() {
		return URL;
	}

	@Override
	@DefaultHandler
	public Resolution view() {
		return new ForwardResolution(defaultJsp());
	}

	@Override
	public String getTitle() {
		return msg("admin.title");
	}

	@Override
	protected String defaultJsp() {
		return JSP;
	}

	@Override
	@Before
	protected void setPageVisitedBoolean() {
		setAdmin();
	}

	public static final String URL = "/admin";

	// App-relative path to the default JSP file
	private static final String JSP = "/WEB-INF/jsp/admin.jsp";

	private static final Log logger = LogFactory.getLog(AdminAction.class);

	private MemberService memberService = SF.member();
	
	
	
	
	
	

	// Modify member form TODO valider
	private Member modifiedMember;
	private String idModified;
	private String firstName;
	private String lastName;
	public String getIdModified(){
		return idModified;
	}
	public void setIdModified(String id){
		this.idModified = id;
	}
	public String getFirstName(){
		return firstName;
	}
	public void setFirstName(String name) {
		this.firstName = name;
	}
	public String getLastName(){
		return lastName;
	}
	public void setLastName(String name){
		this.lastName = name;
	}
	public Member getModifiedMember(){
		return modifiedMember;
	}
	
	public void setModifiedMember(Member member){
		this.modifiedMember = member;
	}
	
	public Resolution modify(){
		modifiedMember = memberService.getMemberFromStringKey(idModified);
		modifiedMember.setFirstName(firstName);
		modifiedMember.setLastName(lastName);
		boolean succeeded = memberService.updateMember(modifiedMember);
		
		if (succeeded) {
			logger.info("Le membre " + modifiedMember.getFirstName()
					+ " " + modifiedMember.getLastName() + " est modifié.");
		} else {
			String errorMessage = "Le membre " + modifiedMember.getFirstName() + " "
					+ modifiedMember.getLastName()
					+ " n'est pas modifié. Un problème est survenu.";
			error(errorMessage);
			logger.error(errorMessage);
		}
		return this.toJsp();
	}
	// TODO fin valider
	
	
	// Member list
	public static final String MEMBER_PAGE_PARAM = "pm";
	
	private int pm = 1;
	private int ppm = Integer.parseInt(Conf.get("pagination.perpage"));
	public void setPm(int page) {
		pm = page;
	}
	public void setPpm(int perPage) {
		ppm = perPage;
	}
	private SearchResult<Member> members;
	@Before(stages = LifecycleStage.CustomValidation)
	private void loadMembers() {
		members = memberService.getMembersOfPage(
				pm, ppm, context.getLocale());
		members.initPagination(getCurrentUrl(), MEMBER_PAGE_PARAM);
	}

	// delegate method
	@ValidationMethod
	public void checkMemberPageValue(ValidationErrors errors) {
		members.checkPageValue(errors);
	}
	// end delegate methods
	
	public SearchResult<Member> getMembers() {
		return members;
	}
	
	public String getNewMemberKey() {
		return ManageMemberAction.NEWMEMBER_MSG_KEY;
	}
	
	public String getDeleteMemberKey() {
		return ManageMemberAction.DELETEMEMBER_MSG_KEY;
	}
	
	public String getNewRoleKey() {
		return ManageMemberAction.NEWROLE_MSG_KEY;
	}
	
	public String getDeleteRoleKey() {
		return ManageMemberAction.DELETEROLE_MSG_KEY;
	}

	// End member list
	

	// Reindexation button

	public Resolution reindex() {
		memberService.rebuildIndex();
		return this.toJsp();
	}

	// End of reindexation button
	

	// Role list
	
	public static final String ROLE_PAGE_PARAM = "pr";
	
	private int pr = 1;
	private int ppr = Integer.parseInt(Conf.get("pagination.perpage"));
	public void setPr(int page) {
		pr = page;
	}
	public void setPpr(int perPage) {
		ppr = perPage;
	}
	private SearchResult<Role> roles;
	@Before(stages = LifecycleStage.CustomValidation)
	private void loadRoles() {
		roles = memberService.getRolesOfPage(pr, ppr, context.getLocale());
		roles.initPagination(getCurrentUrl(), ROLE_PAGE_PARAM);
	}

	// delegate method
	@ValidationMethod
	public void checkRolePageValue(ValidationErrors errors) {
		roles.checkPageValue(errors);
	}
	// end delegate methods
	
	public SearchResult<Role> getRoles() {
		return roles;
	}

	// End role list
	
	
	
	
	
	
	

	
	// Formulaire de réinitialisation des rôles

	public Resolution resetRoles() {
		memberService.resetRoles();
		return this.toJsp();
	}

	// End formulaire de réinitialisation des rôles
	
	
	// Formulaire d'upload de fichier CSV contenant une liste de membres
	
	public String getUploadUrl() {
		return UploadMemberFileAction.getUploadUrl();
	}
	
	private List<String> charsets = null;
	public List<String> getCharsets() {
		if (charsets == null) {
			charsets = new LinkedList<>();
			charsets.add(Charsets.CP1252.getName());
			charsets.add(Charsets.UTF8.getName());
		}
		return charsets;
	}
	
	private List<String> quotechars = null;
	public List<String> getQuotechars() {
		if (quotechars == null) {
			quotechars = new LinkedList<>();
			quotechars.add("\"");
			quotechars.add("'");
		}
		return quotechars;
	}
	
	private List<String> separators = null;
	public List<String> getSeparators() {
		if (separators == null) {
			separators = new LinkedList<>();
			separators.add(";");
			separators.add(",");
		}
		return separators;
	}
	
	private List<String> escapes = null;
	public List<String> getEscapes() {
		if (escapes == null) {
			escapes = new LinkedList<>();
			escapes.add("\\");
		}
		return escapes;
	}
	
	private List<CsvColumn> columns = null;
	public List<CsvColumn> getColumns() {
		if (columns == null) {
			columns = memberService.getAllCsvColumns();
		}
		return columns;
	}
	
	// End upload de membres

}
